package com.hoshiicloud.saleorder.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.query.OmnipotentParam;
import com.hoshiicloud.common.query.OmnipotentWrapper;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.common.utils.BeanUtils;
import com.hoshiicloud.saleorder.entity.OrderMain;
import com.hoshiicloud.saleorder.param.OrderMainAddParam;
import com.hoshiicloud.saleorder.param.OrderMainQueryParam;
import com.hoshiicloud.saleorder.param.OrderMainUpdateParam;
import com.hoshiicloud.saleorder.service.OrderMainService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import java.util.List;
import javax.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 订单信息 控制器
 * </p>
 *
 * @author zhangshuhu
 * @since 2019-06-03
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/saleorder/order-main")
@Api(value = "订单信息", tags = {"订单信息"})
public class OrderMainController {

    @Autowired
    private OrderMainService orderMainService;

    /**
     * @param param
     * @return com.hoshiibuy.common.rpc.Response
     * @description: 分页查询订单信息
     */
    @ApiOperation(value = "分页查询订单信息")
    @PostMapping("/query/page")
    public Response page(@RequestBody @Valid OrderMainQueryParam param) {
        try {
            log.info("分页查询订单信息");
            QueryWrapper<OrderMain> queryWrapper = buildQueryWrapper(param);
            IPage<OrderMain> page = new Page<>(Long.parseLong(param.getPageNumber()),
                    Long.parseLong(param.getPageSize()));
            String key = "OrderMainQueryParam{" + param.toString() + "} ,Page{pageNumber=" + param.getPageNumber()
                    + ",pageSize="
                    + param.getPageSize() + "}";
            // queryWrapper.select(BeanUtils.getSqlSelect(OrderMain.class));
            return Response.data(orderMainService.page(page, queryWrapper, key));
        } catch (Exception e) {
            log.error("分页查询订单信息异常 {}", e.getMessage());
            return Response.failed("分页查询订单信息异常");
        }
    }

    /**
     * 查询主订单信息
     *
     * @param param 查询参数
     * @return Response<OrderMain>
     */
    @ApiOperation(value = "查询主订单信息", notes = "查询所有主订单信息")
    @PostMapping("/list")
    public Response<List<OrderMain>> list(@RequestBody @Valid OrderMainQueryParam param) {
        try {
            log.info("查询主订单信息");
            QueryWrapper<OrderMain> queryWrapper = buildQueryWrapper(param);
            queryWrapper.orderByDesc("created_time");
            return Response.data(orderMainService.list(queryWrapper));
        } catch (Exception e) {
            log.error("查询主订单信息异常 {}", e.getMessage());
            return Response.failed("查询主订单信息异常");
        }
    }

    /**
     * @param id
     * @return com.hoshiibuy.common.rpc.Response
     * @description: 根据id查询订单信息
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询订单信息")
    @ApiParam(name = "id", value = "主键ID", required = true)
    public Response queryById(@PathVariable("id") Long id) {
        return Response.data(orderMainService.getById(id));
    }

    /**
     * @param param
     * @return com.hoshiibuy.common.rpc.Response
     * @description: 新增
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增订单信息")
    public Response save(@RequestBody @Valid OrderMainAddParam param) {
        OrderMain entity;

        try {
            entity = BeanUtils.covertType(param, OrderMain.class);
        } catch (Exception e) {
            log.error("新增订单信息类型转换异常", e);
            return Response.failed("新增订单信息异常");
        }
        return Response.data(orderMainService.save(entity));
    }

    /**
     * @param param
     * @return com.hoshiibuy.common.rpc.Response
     * @description: 修改订单信息
     */
    @PutMapping("/update")
    @ApiOperation(value = "修改订单信息")
    public Response update(@RequestBody @Valid OrderMainUpdateParam param) {
        OrderMain entity;

        try {
            entity = BeanUtils.covertType(param, OrderMain.class);
        } catch (Exception e) {
            log.error("修改订单信息异常", e);
            return Response.failed("修改订单信息失败");
        }
        return Response.data(orderMainService.updateById(entity));

    }

    /**
     * @param id
     * @return com.hoshiibuy.common.rpc.Response
     * @description: 删除订单信息
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "删除订单信息")
    @ApiParam(name = "id", value = "主键ID", required = true)
    public Response delete(@PathVariable("id") Long id) {
        return Response.data(orderMainService.deleteById(id));
    }

    /**
     * @Author:campchen
     * @Description: StringUtils.join(ids, " ") 为缓存中添加唯一KEY  如不合适可选择更好方法
     * @Date:上午 10:18 2019/5/11
     * @Param: ids
     * @return: com.hoshiibuy.common.rpc.Response
     */
    @ApiOperation(value = "根据id集合查询订单信息")
    @GetMapping("/getByIds")
    public Response getByIds(@RequestParam List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return Response.failed("根据主订单ID集合获取主订单信息");
        }
        ids.sort(null);
        return Response.data(orderMainService.getByIds(ids, StringUtils.join(ids, "")));
    }

    /**
     * 构建QueryWrapper
     *
     * @param param 主订单查询参数
     * @return QueryWrapper<OrderMain>
     */
    private QueryWrapper<OrderMain> buildQueryWrapper(OrderMainQueryParam param) {
        QueryWrapper<OrderMain> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(StringUtils.isNotBlank(param.getMainNo()), OrderMain::getMainNo, param.getMainNo())
                .eq(param.getType() != null, OrderMain::getType, param.getType())
                .eq(param.getChannel() != null, OrderMain::getChannel, param.getChannel())
                .eq(param.getSource() != null, OrderMain::getSource, param.getSource())
                .eq(param.getSettlement() != null, OrderMain::getSettlement, param.getSettlement())
                .eq(param.getCompanyId() != null, OrderMain::getCompanyId, param.getCompanyId())
                .eq(param.getPlatformId() != null, OrderMain::getPlatformId, param.getPlatformId())
                .eq(param.getStoreId() != null, OrderMain::getStoreId, param.getStoreId())
                .eq(param.getMemberId() != null, OrderMain::getMemberId, param.getMemberId())
                .eq(StringUtils.isNotBlank(param.getConsignee()), OrderMain::getConsignee, param.getConsignee())
                .eq(param.getCountry() != null, OrderMain::getCountry, param.getCountry())
                .eq(StringUtils.isNotBlank(param.getCountryName()), OrderMain::getCountryName, param.getCountryName())
                .eq(param.getProvince() != null, OrderMain::getProvince, param.getProvince())
                .eq(StringUtils.isNotBlank(param.getProvinceName()), OrderMain::getProvinceName,
                        param.getProvinceName())
                .eq(param.getCity() != null, OrderMain::getCity, param.getCity())
                .eq(StringUtils.isNotBlank(param.getCityName()), OrderMain::getCityName, param.getCityName())
                .eq(param.getDistrict() != null, OrderMain::getDistrict, param.getDistrict())
                .eq(StringUtils.isNotBlank(param.getDistrictName()), OrderMain::getDistrictName,
                        param.getDistrictName())
                .eq(StringUtils.isNotBlank(param.getAddress()), OrderMain::getAddress, param.getAddress())
                .eq(StringUtils.isNotBlank(param.getZipCode()), OrderMain::getZipCode, param.getZipCode())
                .eq(StringUtils.isNotBlank(param.getTelephone()), OrderMain::getTelephone, param.getTelephone())
                .eq(StringUtils.isNotBlank(param.getMobile()), OrderMain::getMobile, param.getMobile())
                .eq(StringUtils.isNotBlank(param.getEmail()), OrderMain::getEmail, param.getEmail())
                .eq(StringUtils.isNotBlank(param.getBestTime()), OrderMain::getBestTime, param.getBestTime())
                .eq(StringUtils.isNotBlank(param.getSignBuilding()), OrderMain::getSignBuilding,
                        param.getSignBuilding())
                .eq(StringUtils.isNotBlank(param.getPostscript()), OrderMain::getPostscript, param.getPostscript())
                .eq(param.getShippingId() != null, OrderMain::getShippingId, param.getShippingId())
                .eq(StringUtils.isNotBlank(param.getShippingName()), OrderMain::getShippingName,
                        param.getShippingName())
                .eq(param.getPayId() != null, OrderMain::getPayId, param.getPayId())
                .eq(StringUtils.isNotBlank(param.getPayName()), OrderMain::getPayName, param.getPayName())
                .eq(StringUtils.isNotBlank(param.getHowOos()), OrderMain::getHowOos, param.getHowOos())
                .eq(StringUtils.isNotBlank(param.getPackName()), OrderMain::getPackName, param.getPackName())
                .eq(param.getPackId() != null, OrderMain::getPackId, param.getPackId())
                .eq(StringUtils.isNotBlank(param.getInvType()), OrderMain::getInvType, param.getInvType())
                .eq(StringUtils.isNotBlank(param.getInvPayee()), OrderMain::getInvPayee, param.getInvPayee())
                .eq(StringUtils.isNotBlank(param.getInvContent()), OrderMain::getInvContent, param.getInvContent())
                .eq(StringUtils.isNotBlank(param.getReferer()), OrderMain::getReferer, param.getReferer())
                .eq(StringUtils.isNotBlank(param.getInvoiceNo()), OrderMain::getInvoiceNo, param.getInvoiceNo())
                .eq(StringUtils.isNotBlank(param.getToBuyer()), OrderMain::getToBuyer, param.getToBuyer())
                .eq(StringUtils.isNotBlank(param.getPayNote()), OrderMain::getPayNote, param.getPayNote())
                .eq(param.getGoodsAmount() != null, OrderMain::getGoodsAmount, param.getGoodsAmount())
                .eq(param.getShippingFee() != null, OrderMain::getShippingFee, param.getShippingFee())
                .eq(param.getInsureFee() != null, OrderMain::getInsureFee, param.getInsureFee())
                .eq(param.getPayFee() != null, OrderMain::getPayFee, param.getPayFee())
                .eq(param.getPackFee() != null, OrderMain::getPackFee, param.getPackFee())
                .eq(param.getTax() != null, OrderMain::getTax, param.getTax())
                .eq(param.getPoints() != null, OrderMain::getPoints, param.getPoints())
                .eq(param.getOrderAmount() != null, OrderMain::getOrderAmount, param.getOrderAmount())
                .eq(param.getAmount() != null, OrderMain::getAmount, param.getAmount())
                .eq(param.getBackAmount() != null, OrderMain::getBackAmount, param.getBackAmount())
                .eq(param.getBenefitsAmount() != null, OrderMain::getBenefitsAmount, param.getBenefitsAmount())
                .eq(param.getBalanceAmount() != null, OrderMain::getBalanceAmount, param.getBalanceAmount())
                .eq(param.getCoinsAmount() != null, OrderMain::getCoinsAmount, param.getCoinsAmount())
                .eq(param.getDeleted() != null, OrderMain::getDeleted, param.getDeleted())
                .eq(param.getPaidTime() != null, OrderMain::getPaidTime, param.getPaidTime())
                .eq(param.getCancelledTime() != null, OrderMain::getCancelledTime, param.getCancelledTime())
                .eq(param.getDeliveryTime() != null, OrderMain::getDeliveryTime, param.getDeliveryTime())
                .eq(param.getReceivedTime() != null, OrderMain::getReceivedTime, param.getReceivedTime())
                .eq(param.getOrderStatus() != null, OrderMain::getOrderStatus, param.getOrderStatus())
                .eq(param.getShippingStatus() != null, OrderMain::getShippingStatus, param.getShippingStatus())
                .eq(param.getPayStatus() != null, OrderMain::getPayStatus, param.getPayStatus())
                .eq(param.getServiceStatus() != null, OrderMain::getServiceStatus, param.getServiceStatus());
        return queryWrapper;
    }


    @ApiOperation(value = "根据自定义条件查询商品主单信息")
    @PostMapping("/omniQueryOrderMain")
    public Response omniQueryOrderMain(@RequestBody List<OmnipotentWrapper> wrappers) {
        String key = wrappers.toString();
        List<OrderMain> orderMains = orderMainService.omniQueryOrderMain(wrappers,key);
        return Response.data(orderMains);
    }

}
